package model.textChat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import model.infocenter.ClientUserInformations;
import model.textChat.Interface.MessageObserver;


public class MessageRecordManager implements MessageObserver
{
	private MessageRecorder mRecorder;
	private File recordFile;
	
	public MessageRecordManager()
	{
		ClientUserInformations clientUser = ClientUserInformations.getInstance();
		int roomId = clientUser.getCurRoomId();
		String path = "TextChatRecord/" + roomId + ".txt";
		recordFile = new File( path );
		
		if ( recordFile.exists() )
		{
			try
			{
				ObjectInputStream oReader = new ObjectInputStream( new FileInputStream( recordFile ) );
				mRecorder = (MessageRecorder)oReader.readObject();
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			mRecorder = new MessageRecorder();
		}
	}
	
	@Override
	public void update(Message message)
	{
		mRecorder.append( message );
	}
	
	public void viewMessageRecord()
	{
		mRecorder.reset();
	}
	
	public Message readNextRecord()
	{
		return mRecorder.readNextRecord();
	}
	
	public void end()
	{
		recordFile.getParentFile().mkdirs();
		try
		{
			recordFile.createNewFile();
			ObjectOutputStream oWriter = new ObjectOutputStream( new FileOutputStream( recordFile ) );
			oWriter.writeObject( mRecorder );
		
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
}
